/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import React, {useCallback, useEffect, useState} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ImageBackground,
  FlatList,
  Dimensions,
} from 'react-native';
import {
  GridCol,
  GridRow,
} from '@hadss/react_native_adaptive_layout';
import debounce from 'lodash.debounce';
import TabButtom from './components/TabButtom';
import {ImageData} from './mock/index';

const App = (): JSX.Element => {
  const [currentBp, setCurrentBp] = useState<string>('unknown');
  const BIGSCREEN = 840;
  const MIDDLESCREEN = 600;
  const CONTANIERPADDING = 16;
  const ITEMGAP = 8;
  // 断点
  const onBreakpointChange = useCallback(
    debounce((bp: string) => {
      setCurrentBp(bp);
    }, 300),
    [],
  );
  // 获取屏幕宽度
  const [screenViewWidth, setScreenViewWidth] = useState(
    Dimensions.get('window').width,
  );
  useEffect(() => {
    onGetListWidth();
    const subscription = Dimensions.addEventListener('change', () => {
      setScreenViewWidth(Dimensions.get('window').width);
    });
    return (): void => subscription.remove();
  }, []);
  // 计算内容宽度
  const onGetListWidth = (): number => {
    if (currentBp === 'lg' || currentBp === 'xl') {
      return onGetTab(screenViewWidth * 11 / 12);
    } else {
      return onGetTab(0);
    }
  };
  const onGetListLeftSpace = (index: number): number => {
    const columns = getColumns();
    const isFirstInRow = (index + 1) % columns === 1;
    return isFirstInRow ? CONTANIERPADDING : ITEMGAP;
  };
  const onGetTab = (tab: number): number => {
    const columns = getColumns();
    return (
      (screenViewWidth -
        tab -
        2 * CONTANIERPADDING -
        (columns - 1) * ITEMGAP) /
      columns
    );
  };
  
  const renderItem = ({item, index}): JSX.Element => (
    <View
      style={{
        width: onGetListWidth(),
        marginLeft: onGetListLeftSpace(index),
        marginRight: (index + 1) % getColumns() === 0 ? CONTANIERPADDING : 0,
        overflow: 'hidden',
        marginBottom: 10,
        flex: 1,
      }}>
      <View>
        <ImageBackground
          source={item.url}
          style={styles.backgroundImage}
        />
      </View>
      <Text numberOfLines={1} ellipsizeMode="tail" style={styles.titleItem}>
        {item.title}
      </Text>
      <Text
        numberOfLines={1}
        ellipsizeMode="tail"
        style={styles.descriptionItem}>
        {item.description}
      </Text>
    </View>
  );

  // 定义断点
  const getColumns = (): number => {
    if (screenViewWidth >= BIGSCREEN) {
      return 4;
    }
    if (screenViewWidth >= MIDDLESCREEN) {
      return 3;
    } else {
      return 2;
    }
  };

  const filledData =
  ImageData.length % getColumns() === 0
    ? ImageData
    : [
        ...ImageData,
        ...Array(getColumns() - (ImageData.length % getColumns())).fill({
          isEmpty: true,
          id: 'empty',
        }),
      ];

  const ListHeader = (): React.ReactNode => {
    return (
      <View style={styles.listTitle}>
        <Text style={{fontSize: 20}}>Tab A1</Text>
        <Text style={styles.tabText}>Tab A2</Text>
        <Text style={styles.tabText}>Tab A3</Text>
        <Text style={styles.tabText}>Tab A4</Text>            
      </View>
    );
  };

  const HomeScreen = (): JSX.Element => {
    return (
      <View style={{flex: 1, backgroundColor: '#fff'}}>
        <GridRow
          onBreakpointChange={onBreakpointChange}
          style={{flex: 1}}
          columns={12}>
          {/* 此处测试根据xl断点添加相应布局 */}
          {/* 大屏侧边栏 */}
          {currentBp === 'lg' && (
            <GridCol span={{xs: 0, sm: 0, md: 0, lg: 1}} offset={0} order={0}>
              <TabButtom currentBp={currentBp} type={1} />
            </GridCol>
          )}
          {/* 视频列表页 */}
          <GridCol span={{xs: 12, sm: 12, md: 12, lg: 11}}>
            {/* 顶部Tab */}
            {ListHeader()}
            {/* 滚动 */}
            <FlatList
                data={filledData}
                numColumns={getColumns()}
                key={`columns-${getColumns()}`}
                contentContainerStyle={{
                  justifyContent: 'flex-start', // 自动均匀分布
                }}
                showsVerticalScrollIndicator={false}
                keyExtractor={(item): string => item.id.toString()}
                renderItem={renderItem}
              />
            {/* Bottom */}
            {(currentBp === 'sm' ||
              currentBp === 'md' ||
              currentBp === 'xs') && (
              <TabButtom currentBp={currentBp} type={2} />
            )}
          </GridCol>
        </GridRow>
      </View>
    );
  };
  return (
    <HomeScreen/>
  );
};

const styles = StyleSheet.create({
  gridRow: {
    flex: 1,
  },
  backgroundImage: {
    flex: 1,
    borderRadius: 15,
    overflow: 'hidden',
    aspectRatio: 1.6,
  },
  titleItem: {
    marginTop: 4,
    fontWeight: 'bold',
    fontSize: 14,
  },
  descriptionItem: {
    marginTop: 4,
    fontWeight: 'normal',
    fontSize: 12,
  },
  listTitle: {
    flexDirection: 'row',
    width: '100%', 
    height: 50,
    marginTop: 50,
    marginLeft: 20,
  },
  tabText: {
    fontSize: 15,
    marginLeft: 8,
    marginTop: 4,
    color: '#535353ff',
  }
});

export default App;
